/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-13 14:56:49
 * @LastEditTime: 2023-09-04 13:28:25
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import {
  Box,
  ButtonGroup,
  Center,
  Flex,
  Heading,
  Modal,
  ModalBody,
  ModalCloseButton,
  ModalContent,
  ModalHeader,
  ModalOverlay,
  Spinner,
  Text,
  useDisclosure,
} from '@chakra-ui/react';
import { useLazyListImagesQuery, useListImagesQuery } from '@tourfly/api';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FaCartArrowDown, FaCheck, FaTimes } from 'react-icons/fa';
import { HiViewGridAdd } from 'react-icons/hi';
import Masonry from 'react-masonry-css';
import { useNavigate } from 'react-router-dom';

import GalleryBoardName from '~/features/Gallery/components/GalleryBoardName';

import IAIButton from '@/common/components/IAIButton';
import IAIIconButton from '@/common/components/IAIIconButton';
import ChangeBoardModal from '@/features/ChangeBoardModal/components/ChangeBoardModal';
import BoardsList from '@/features/Gallery/Boards/BoardsList/BoardsList';
import GalleryImageItem from '@/features/Gallery/components/GalleryImageItem';
import ImageDetail from '@/features/Gallery/components/ImageDetail';

import { useBoardTotal } from '@/features/Gallery/hooks/useBoardTotal';
import { selectListImagesBaseQueryArgs } from '@/features/Gallery/store/gallerySelectors';
import { IMAGE_LIMIT } from '@/features/Gallery/store/types';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { handDownloadImages, setDownloadImages } from '@/store/user';
const breakpointColumnsObj = {
  default: 7,
  2160: 6,
  1800: 5,
  1580: 4,
  1260: 3,
  1000: 2,
  600: 2,
  400: 1,
};
const DownloadToolBtns = () => {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const { downloadImages, downloadImagesList } = useAppSelector(
    (state) => state.user
  );
  return (
    <ButtonGroup size="sm" isAttached w="max-content" justifyContent="stretch">
      {downloadImagesList.length > 0 && (
        <IAIIconButton
          aria-label={t('gallery.requestDownloadImages')}
          tooltip={t('gallery.requestDownloadImages')}
          icon={<FaCheck />}
          onClick={() => dispatch(handDownloadImages())}
        />
      )}
      {!downloadImages && (
        <IAIIconButton
          aria-label={t('gallery.downloadImages')}
          tooltip={t('gallery.downloadImages')}
          data-selected={downloadImages}
          icon={<FaCartArrowDown />}
          onClick={() => dispatch(setDownloadImages())}
        />
      )}
      {downloadImages && (
        <IAIIconButton
          aria-label={t('gallery.cancel')}
          tooltip={t('gallery.cancel')}
          icon={<FaTimes />}
          onClick={() => dispatch(setDownloadImages())}
        />
      )}
    </ButtonGroup>
  );
};
export default function Gallery() {
  const { t } = useTranslation();
  const [showDetailImage, setShowDetailImage] = useState<string | null>('');

  const { downloadImagesList } = useAppSelector((state) => state.user);

  const {
    isOpen: modalIsOpen,
    onOpen: modalOnOpen,
    onClose: modalOnClose,
  } = useDisclosure();

  const navigator = useNavigate();

  const selectedBoardId = useAppSelector(
    (state) => state.gallery.selectedBoardId
  );
  const { currentViewTotal } = useBoardTotal(selectedBoardId);
  const queryArgs = useAppSelector(selectListImagesBaseQueryArgs);

  const { currentData, isFetching, isSuccess, isError } =
    useListImagesQuery(queryArgs);

  const [listImages] = useLazyListImagesQuery();

  const areMoreAvailable = useMemo(() => {
    if (!currentData || !currentViewTotal) {
      return false;
    }
    return currentData.ids.length < currentViewTotal;
  }, [currentData, currentViewTotal]);

  const handleLoadMoreImages = useCallback(() => {
    if (!areMoreAvailable) {
      return;
    }

    listImages({
      ...queryArgs,
      offset: currentData?.ids.length ?? 0,
      limit: IMAGE_LIMIT,
    });
  }, [areMoreAvailable, listImages, queryArgs, currentData?.ids.length]);

  useEffect(() => {
    if (!modalIsOpen) {
      setShowDetailImage(null);
    }
  }, [modalIsOpen]);

  const { isOpen: isBoardListOpen, onToggle: onToggleBoardList } =
    useDisclosure();

  return (
    <Box w="full" p="2">
      <Box pb="2">
        <Flex
          sx={{
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 2,
          }}
        >
          <GalleryBoardName
            isOpen={isBoardListOpen}
            onToggle={onToggleBoardList}
          />
          <DownloadToolBtns />
        </Flex>
        <BoardsList isOpen={isBoardListOpen} />
      </Box>
      {!currentData && (
        <Center h="96">
          <Spinner />
        </Center>
      )}
      {isSuccess && currentData?.ids.length === 0 && (
        <Box
          role="group"
          p={6}
          w="auto"
          m="10"
          boxShadow="xl"
          rounded="lg"
          bg="base.950"
          pos="relative"
          zIndex={1}
          cursor="pointer"
          onClick={() => navigator('/aigc')}
        >
          <Flex
            minH="20rem"
            direction="column"
            justify="center"
            align="center"
            color="base.100"
          >
            <HiViewGridAdd fontSize="6rem" />
            <Heading size="lg" textAlign="center">
              创作作品
            </Heading>
          </Flex>
        </Box>
      )}
      {isSuccess && currentData && (
        <Box
          overflowY="scroll"
          sx={{
            '.tag-masonry-grid': {
              width: '100%',
              display: 'flex',
              gap: '4',
            },
            '.tag-masonry-grid_column': {
              display: 'flex',
              flexDirection: 'column',
              gap: '4',
            },
          }}
        >
          <Masonry
            breakpointCols={breakpointColumnsObj}
            className="tag-masonry-grid"
            columnClassName="tag-masonry-grid_column"
          >
            {currentData.ids.map((imageName) => (
              <GalleryImageItem
                key={imageName}
                imageName={imageName as string}
                hiddenToolButton
                isDownloadSelected={
                  !!downloadImagesList.find((i) => i.image_name === imageName)
                }
                onOpenModal={() => {
                  modalOnOpen();
                  setShowDetailImage(imageName as string);
                }}
              />
            ))}
          </Masonry>
          <Flex justify="center" py="4">
            {areMoreAvailable ? (
              <IAIButton
                onClick={handleLoadMoreImages}
                isDisabled={!areMoreAvailable}
                isLoading={isFetching}
                loadingText="加载中"
                flexShrink={0}
              >
                {`${t('gallery.loadMore')} (${
                  currentData.ids.length
                } / ${currentViewTotal})`}
              </IAIButton>
            ) : (
              <Text color="base.400" fontSize="sm" pt="6">
                {t('gallery.allImagesLoaded')}
              </Text>
            )}
          </Flex>
        </Box>
      )}
      <Modal
        isOpen={modalIsOpen && showDetailImage}
        onClose={() => {
          modalOnClose();
        }}
        size={{ base: 'sm', md: '6xl' }}
        isCentered
        scrollBehavior="inside"
      >
        <ModalOverlay />
        <ModalContent fontFamily="Inter">
          <ModalCloseButton />
          <ModalHeader fontWeight="bold" pb={3}></ModalHeader>
          <ModalBody>
            {showDetailImage && (
              <ImageDetail showDetailImage={showDetailImage} />
            )}
          </ModalBody>
        </ModalContent>
      </Modal>
      <ChangeBoardModal />
    </Box>
  );
}
